from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
from ..config.database import Base

# 用户与聊天室的多对多关联表
user_chat_room = Table(
    'user_chat_room',
    Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('chat_room_id', Integer, ForeignKey('chat_rooms.id'), primary_key=True)
)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True, nullable=False)
    password = Column(String, nullable=False)  # 存储加密后的密码
    email = Column(String, unique=True, index=True, nullable=False)
    avatar = Column(String, nullable=True)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    last_login = Column(DateTime(timezone=True), nullable=True)
    role = Column(String, default="USER", nullable=False)  # 默认角色为普通用户，管理员为"ADMIN"

    # 用户与聊天室的多对多关系
    chat_rooms = relationship("ChatRoom", secondary=user_chat_room, back_populates="members")
    
    # 用户与API Key的一对多关系
    api_keys = relationship("ApiKey", back_populates="user", cascade="all, delete-orphan")
    
    # 判断是否为管理员
    def is_admin(self):
        return self.role == "ADMIN"